<template>
<!--  <a-card :bordered="false" :style={height:vdaH}>-->
  <a-card :bordered="false" >
    <a-form layout="inline" >
      <a-row :gutter="24">
        <a-col :xl="8" :lg="8" :md="8" :sm="24">
          <a-form-item label="时间">
            <g-year-picker
              placeholder="请选择时间"
              :is-init="false"
              v-model="date"
            ></g-year-picker>
          </a-form-item>
        </a-col>
        <a-col :xl="16" :lg="16" :md="16" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button style="margin-left: 20px"  class="Template" type="primary" icon="download" @click="handleExportXlsTemplate('育人与服务')">下载模板</a-button>
                <a-upload v-show="value.id != 'A05'" name="file" style="margin-left: 20px" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel" v-has="'user:education-service-operate'">
                  <a-button type="primary" icon="import">导入</a-button>
                </a-upload>
            </span>
        </a-col>
      </a-row>
    </a-form>
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{x:true}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">
        <template slot="teacherTypeSlot" slot-scope="text, record">
          <a-tag v-if="text=='1-1'" color="#87d068">专职教师</a-tag>
          <a-tag v-else color="#1890FF">兼职教师</a-tag>
        </template>

        <template slot="pointSlot" slot-scope="text, record">
          <a-tag v-if="text<0" color="#87d068">无</a-tag>
          <a-tag v-else color="#1890FF">{{ text }}</a-tag>
        </template>

        <template slot="resultSlot" slot-scope="text, record">
          <a-tag v-if="record.point<0" color="#1890FF">不考核</a-tag>
          <a-tag v-else-if="record.score>=record.point" color="#87d068">达标</a-tag>
          <a-tag v-else color="#f50">不达标</a-tag>
        </template>

      </a-table>
    </div>
  </a-card>
</template>

<script>
import { ACCESS_TOKEN, CURRENT_DATE, TENANT_ID } from '@/store/mutation-types'
import { Modal } from 'ant-design-vue'
import store from '@/store'
import Vue from 'vue'
import { downFile, getAction } from '@api/manage'
import GYearPicker from '@views/gfxy/common/GYearPicker'
import { GfxyListMixin } from '../../../mixins/GfxyListMixin'

export default {
  name: "EducationAndServiceImport",
  props: ['value'],
  mixins:[GfxyListMixin],
  components:{GYearPicker},
  data(){
    return {
      vdaH: '0px',
      orgCode:'',
      date:'',
      url:{
        list:'/common/totalScore/getEducationTotalScore',
        handleExportXlsTemplate:"/educationandservice/educationAndServiceImport/exportXlsTemplate",
        importExcelUrl:"/educationandservice/educationAndServiceImport/importExcel",
      },
      loading:false,
      ipagination:{
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      dataSource:[],
      columns:[
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'部门',
          align:"center",
          dataIndex: 'teachingOrgCode_dictText'
        },
        {
          title:'教师姓名',
          align:"center",
          dataIndex: 'realname'
        },
        {
          title:'教师类型',
          align:"center",
          dataIndex: 'teacherType',
          scopedSlots: {customRender: 'teacherTypeSlot'}
        },
        {
          title:'职称',
          align:"center",
          dataIndex: 'titleRank_dictText'
        },
        // {
        //   title:'基本指标值',
        //   align:"center",
        //   dataIndex: 'point',
        //   scopedSlots: {customRender: 'pointSlot'}
        // },
        {
          title:'总积分',
          align:"center",
          dataIndex: 'score'
        }
        // ,
        // {
        //   title:'考核结果',
        //   align:"center",
        //   scopedSlots: {customRender: 'resultSlot'}
        // }
      ],
    }
  },
  created(){
    this.initCurrent();
  },
  methods:{
    initCurrent(){
      this.date = Vue.ls.get(CURRENT_DATE);
    },
    searchQuery(){

    },
    loadData(arg){
      if(!this.url.list){
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      if(this.value.id == 'A05'){
        console.log("不查询");
        return;
      }
      let params =  {date: this.date, orgCode: this.value.id,pageNo:this.ipagination.current,pageSize:this.ipagination.pageSize}//查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {

        if (res.success) {
          console.log(res)
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records||res.result;
          console.log("dataSource",this.dataSource)
          if(res.result.total)
          {
            this.ipagination.total = res.result.total;
          }else{
            this.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        }
        if(res.code===510){
          this.$message.warning(res.message)
        }
        this.loading = false;
      })


    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.ipagination = pagination;
      this.loadData();
    },
    handleExportXlsTemplate(fileName){
      if(!fileName || typeof fileName != "string"){
        fileName = "导出文件"
      }
      let param = {orgCode: this.value.id}

      console.log("导出参数",param)
      downFile(this.url.handleExportXlsTemplate,param).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName+'.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    /* 导入 */
    handleImportExcel(info){
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }

      if (info.file.status === 'done') {

        if (info.file.response.success) {
          if (info.file.response.result.code === 201) {

            let { message, result: { msg, fileUrl, fileName } } = info.file.response.result
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (<div>
                  <span>{msg}</span><br/>
                  <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.result.message || `${info.file.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`);
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes("Token失效")) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload();
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        }
      }
    },
  },
  computed: {
    //token header
    tokenHeader(){
      let head = {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)}
      let tenantid = Vue.ls.get(TENANT_ID)
      if(tenantid){
        head['tenant-id'] = tenantid
      }
      return head;
    },
  },
  watch:{
    value(newVal){
      console.log("value newVal", newVal)
      if(newVal.id){
        this.loadData();
      } else {
        console.log(newVal.id)
      }

    }
  },
  mounted() {
    // let h = document.documentElement.clientHeight || document.body.clientHeight;
    // this.vdaH = h - 265 + 'px';
    // window.onresize = () => {
    //   return (() => {
    //     let h = document.documentElement.clientHeight || document.body.clientHeight;
    //     this.vdaH = h - 265 + 'px';
    //     console.log(this.vdaH)
    //   })()
    // };
  }
}
</script>

<style scoped>

</style>